#encoding=utf-8
import requests
import time
import os
from PIL import Image
from tqdm import tqdm
import logging
import configparser

logging.basicConfig(format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                    level=logging.INFO,
                    filename='down_setu.log',
                    filemode='a',
                    encoding='utf-8')


cf = configparser.ConfigParser()
cf.read("config.ini")  # 读取配置文件，如果写文件的绝对路径，就可以不用os模块
path=cf.get('user1', 'down_path')
if os.path.exists(path):
    logging.info('存在文件夹')
else:
    os.mkdir(path)
    logging.info('正在创建文件夹')


def download_and_verify():
    api = 'https://api.lolicon.app/setu/v2?r18=1'
    res = requests.get(url=api).json()

    data:str = res['data'][0]
    pid:int = data['pid']
    ext = data['ext']
    url = requests.get(data['urls']['original'], stream=True)  # 使用 stream=True 参数以流的方式下载文件
    filename = './r18/'+str(pid)+'.'+ext
    logging.info(data)

    total_size = int(url.headers.get('content-length', 0))  # 获取文件总大小
    with open(filename, 'wb') as f:
        with tqdm(total=total_size, desc=f'Downloading {filename}', unit='B', unit_scale=True, unit_divisor=1024, colour='green') as pbar:
            for data_chunk in url.iter_content(chunk_size=1024):
                f.write(data_chunk)
                pbar.update(len(data_chunk))

    logging.info('Download completed!')

    try:
        Image.open(filename).verify()
        # logging.info('图片完好')
    except:
        logging.info('图片已损坏')
        os.remove(filename)
        logging.info('图片已删除')
    time.sleep(0.5)

download_count = 0
count = int(cf.get('user1', 'count'))
while download_count < count:  # 设置下载次数
    try:
        download_and_verify()
        download_count += 1
    except Exception as e:  # 添加异常处理
        logging.info('e')
        print
        time.sleep(0.5)